#!/usr/bin/perl

# commun sub program to generate keyword content
sub generate_keyword {
	# pattern as in the raw source file
	$pattern = $_[0];
	# keyword value from git log
	$value = $_[1];

	# extract pattern start
	$start = substr($pattern,0,2);
	if ($start eq "::") {
		# if it start with "::", the pattern length must be preserved
		return ":: " . $value . (' ' x (length($pattern) - length($value) - 3));
	} else {
		# return default content without length concern
		return ": " . $value . " ";
	}
}

# get first argument (full path name)
$path = shift;

if (0 < length($path)) {
	# extract file name
	$path =~ /.*\/(.*)/;
	$filename = $1;

	# not a full path, return the entire path as file name
	if (0 == length($filename)) {
		$filename = $path;
	}

	# Need to grab filename and to use git log for this to be accurate.
	use IPC::Open3;
	$pid = open3(0,\*READ,\*ERROR,"git", "log", "-n", "1", "--format=%H%n%an%n%ai%n", "--", "$path");
	waitpid( $pid, 0 );

	# read error pipe
	chomp($error = <ERROR>);

	# if there is no error message
	if (0 == length($error)) {
		# read the 3 output lines of svn log
		chomp($revision = <READ>); # 1st line is revision hash
		chomp($author = <READ>);   # 2nd line is author name
		chomp($date = <READ>);     # 3rd line is date
		
		# some usefull debug stuff
		# print("$revision\n$author\n$date\n");
		
		# main processing loop
		
		# read from stdin
		while (<STDIN>) {
			# replace keyword "Date"
			s/\$([Dd][Aa][Tt][Te])([^\$]*)\$/"\$" . $1 . generate_keyword($2,$date) . "\$"/eg;

			# replace keyword "Author"
			s/\$([Aa][Uu][Tt][Hh][Oo][Rr])([^\$]*)\$/"\$" . $1 . generate_keyword($2,$author) . "\$"/eg;

			# replace keyword "Id"
			s/\$([Ii][Dd])([^\$]*)\$(.*)/"\$" . $1 . generate_keyword($2,$path . " " . $author . " " . date) . "\$"/eg;

			# replace keyword "Url"
			s/\$([Uu][Rr][Ll])([^\$]*)\$/"\$" . $1 . generate_keyword($2,$path) . "\$"/eg;

			# replace keyword "File"
			s/\$([Ff][Ii][Ll][Ee])([^\$]*)\$/"\$" . $1 . generate_keyword($2,$filename) . "\$"/eg;

			# replace keywords "Revision" and "Rev"
			s/\$([Rr][Ee][Vv][Ii][Ss][Ii][Oo][Nn])([^\$]*)\$/"\$" . $1 . generate_keyword($2,$revision) . "\$"/eg;
			s/\$([Rr][Ee][Vv])([^Ii][^\$]*|)\$/"\$" . $1 . generate_keyword($2,$revision) . "\$"/eg;

		} continue {
			# output generated text to stdout
			print;
		}
	}
}
